<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <!-- 图表容器 -->
    <div ref="chart" class="chart-container"></div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';

export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  setup() {
    // 响应式数据
    const chart = ref(null); // 图表容器引用
    let chartInstance = null; // 图表实例

    // 生命周期钩子
    onMounted(() => {
      // 初始化图表
      chartInstance = echarts.init(chart.value, 'dark');
      
      // 配置图表
      chartInstance.setOption({
        title: { text: 'Vue ECharts Demo' },
        tooltip: {},
        xAxis: {
          data: ['A', 'B', 'C', 'D', 'E']
        },
        yAxis: {},
        series: [{
          name: '示例',
          type: 'bar',
          data: [5, 20, 36, 10, 10]
        }]
      });
    });

    // 组件卸载前清理
    onBeforeUnmount(() => {
      if (chartInstance) {
        chartInstance.dispose();
        chartInstance = null;
      }
    });

    return {
      chart // 返回模板引用
    };
  }
};
</script>

<style scoped>
.chart-container {
  width: 600px;
  height: 400px;
  margin: 40px auto;
}
</style>